import { randomUUID } from 'node:crypto';

import { defineEventHandler, readBody } from 'h3';

export default defineEventHandler(async (event) => {
  const body = await readBody(event);

  // 验证必要字段
  if (!body.listingId || !body.buyer || !body.duration) {
    return {
      code: 400,
      data: null,
      msg: '缺少必要字段：listingId, buyer, duration',
    };
  }

  // 生成订单ID
  const orderId = `ORDER_${Date.now()}_${randomUUID().slice(0, 8).toUpperCase()}`;

  // 模拟创建订单
  const order = {
    id: orderId,
    listingId: body.listingId,
    listingTitle: body.listingTitle || '资源商品',
    buyer: {
      id: body.buyer.id,
      name: body.buyer.name,
      avatar: body.buyer.avatar || '/images/users/default.jpg',
      phone: body.buyer.phone,
      email: body.buyer.email,
    },
    seller: {
      id: body.seller.id,
      name: body.seller.name,
      avatar: body.seller.avatar || '/images/sellers/default.jpg',
      phone: body.seller.phone,
      email: body.seller.email,
    },
    status: 'pending_payment',
    statusName: '待支付',
    price: {
      currency: body.price?.currency || 'CNY',
      originalPrice: body.price?.originalPrice || 0,
      finalPrice: body.price?.finalPrice || body.price?.originalPrice || 0,
      discount:
        (body.price?.originalPrice || 0) -
        (body.price?.finalPrice || body.price?.originalPrice || 0),
      unit: body.price?.unit || 'month',
    },
    quantity: body.quantity || 1,
    duration: {
      startDate: body.duration.startDate,
      endDate: body.duration.endDate,
      ...body.duration,
    },
    totalAmount:
      (body.price?.finalPrice || body.price?.originalPrice || 0) *
      (body.quantity || 1),
    deposit: Math.round(
      (body.price?.finalPrice || body.price?.originalPrice || 0) *
        (body.quantity || 1) *
        0.2,
    ), // 20% 定金
    payment: {
      method: '',
      status: 'pending',
      paidAmount: 0,
      paymentDeadline: new Date(
        Date.now() + 7 * 24 * 60 * 60 * 1000,
      ).toISOString(), // 7天后过期
    },
    requirements: {
      usage: body.requirements?.usage || '',
      specialNeeds: body.requirements?.specialNeeds || '',
      contactTime: body.requirements?.contactTime || '工作日 9:00-18:00',
    },
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    notes: body.notes || '',
  };

  // 计算余款
  order.balance = order.totalAmount - order.deposit;

  return {
    code: 0,
    data: order,
    msg: '订单创建成功',
  };
});
